package com.banciyuan.bcywebview.biz.detail;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.utils.baidussp.SimpleImplOnAdlistener;
import com.banciyuan.bcywebview.utils.baidussp.SspHelper;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by squall1989 on 2017/2/21.
 */

public class AdHelper {

    private Context mContext;
    private String adposition;

    public AdHelper(Context mContext, String adposition) {
        this.mContext = mContext;
        this.adposition = adposition;
    }

    public void parseHtml(ImageView imageView, View view, String html) {
        final String[] arrays = new String[2];
        Pattern p1 = Pattern.compile("url=(\\S+)\\\\\\\"");
        Pattern p2 = Pattern.compile("<img src=\\\\\\\"(\\S+)\\\\\\\"");

        final Matcher m1 = p1.matcher(html);
        Matcher m2 = p2.matcher(html);
        if (m1.find()) {
            arrays[0] = m1.group(1);
        }
        if (m2.find()) {
            arrays[1] = m2.group(1);
        }
        if (arrays.length == 2) {
            if (!TextUtils.isEmpty(arrays[1])) {
                view.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.VISIBLE);
                ImageLoader.getInstance().displayImage(arrays[1], imageView, ImageOptions.options_none);
            } else {
                view.setVisibility(View.GONE);
                imageView.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(arrays[0])) {
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            SspHelper sspHelper = new SspHelper(mContext);
                            sspHelper.getClickCount(adposition, new SimpleImplOnAdlistener());
                            Intent intent = new Intent(mContext, WebActivity.class);
                            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, Uri.decode(arrays[0]));
                            mContext.startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } else {
            view.setVisibility(View.GONE);
            imageView.setVisibility(View.GONE);
        }

    }
}
